package com.dadibadi.core.auth.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dadibadi.core.auth.qo.UserAccountEditQO;
import com.dadibadi.core.auth.service.UserAccountService;
import com.dadibadi.core.auth.vo.UserAccountDetailVO;
import com.dadibadi.core.auth.vo.UserAccountListVO;
import com.dadibadi.core.common.exception.MyBizException;
import com.dadibadi.core.common.utils.MD5Util;
import com.dadibadi.core.dao.entity.SysRoleTab;
import com.dadibadi.core.dao.mapper.SysRoleMapper;
import com.venusoft.developer.common.result.CommonResult;
import com.venusoft.developer.common.result.ICommonResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * TODO
 *
 * @author : lkfs@163.com
 * @date : 2025-08-15 10:28
 */

@RestController
@RequestMapping("/auth")
@Slf4j
@Tag(name = "api/auth认证", description = "")
public class ApiUserAccountLoginController {


    @Resource
    private UserAccountService userAccountService;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @PostMapping("/api-user-account-get")
    @Operation(summary = "用户登录", description = "")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", content = {@Content(schema = @Schema(implementation = UserAccountDetailVO.class), mediaType = "application/json")})})
    public ICommonResult exec(
            @RequestBody @Parameter(required = true) @Validated UserAccountEditQO qo,
            @RequestHeader(required = false) String platform,
            @RequestHeader(required = false) String version,
            HttpServletRequest request) {
        UserAccountListVO vo = userAccountService.getUserAccount(qo);
        String password = MD5Util.sha256Hex(qo.getPassword());
        if (!password.equals(vo.getPassword())) {
            throw MyBizException.PASSWORD_ERROR;
        }

        List<SysRoleTab> userRoleTabs = sysRoleMapper.selectList(Wrappers.<SysRoleTab>lambdaQuery()
                .eq(SysRoleTab::getUserId,vo.getUserId()));
        vo.setRoleSet(userRoleTabs.stream().map(SysRoleTab::getRoleType).toList());
        userAccountService.attachAdminToken(vo);
        return new CommonResult<>(vo);


    }
}
